#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import os

from django.http import HttpResponseRedirect
from django.urls import reverse

from utils import Logger
from django.conf.urls import url

from utils.ActionSession import readActionSession, createActionSession, updateActionSession
from utils.MyJsonResponse import errorDaemon, successResponse, errorResponse, MyJsonResponse

logger = Logger.Logger().getLogger()



def urls():
    urlpatterns = [
        url(r'^$', index),
        url(r'^list/', list),
        url(r'^tailLog/', tailLog),

    ]
    return urlpatterns, 'tailLog', 'tailLog'

def index(request):
    return errorDaemon("test1")


def tailLog(request):
    if len(request.body) == 0:
        return errorResponse("request.body无数据")
    d = json.loads(request.body)


    if "daemonSessionId" not in d.keys():
        print("non daemonSessionId")
        # 无进度查看日志
        path = d["path"]
        if path is None:
            return errorDaemon("path不能为空")
        tailSession = {}
        daemonSessionId=createActionSession(tailSession)

    else:
        print("has daemonSessionId")
        daemonSessionId=d["daemonSessionId"]
        tailSession = readActionSession(daemonSessionId)
        path = tailSession["path"]

    lineTotal=0
    if "daemonSessionId" not in d.keys():

        if "firstLinenum" in d.keys():
            linenum=d["firstLinenum"]
        else:
            for index, line in enumerate(open(path, 'r')):
                lineTotal += 1
            linenum = lineTotal-500
            if linenum <0:
                linenum=0
    else:
        linenum = tailSession["linenum"]

    print("linenum=%s",linenum)
    data=[]
    newLinenum=linenum;
    for index, line in enumerate(open(path, 'r')):
        if index+1 > linenum:
            newLinenum=index+1
            data.append({"linenum":newLinenum,"line":line})

    updateActionSession(daemonSessionId,{"path":path,"linenum":newLinenum})

    data={"lineContent":data,"daemonSessionId":daemonSessionId}

    return successResponse("",data=data)

def list(request):
    if len(request.body) == 0:
        return errorResponse("request.body无数据")
    d = json.loads(request.body)
    path = d["path"]
    if path is None:
        return errorDaemon("path不能为空")
    return listFile(request,path)


def listFile(request,path):

    data=[]

    for  root, dirs, files in os.walk(path):
        for dir in dirs:
            f={"type":1,"path":root+"/"+dir,"name":dir}
            data.append(f)
        for file in files:
            data.append({"type":0,"path":root+"/"+file,"name":file})
        break

    return successResponse("成功",data=data)
